#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
本地简易服务器：接收周次参数，返回课表 HTML
运行：python server.py
然后在浏览器访问 http://localhost:8000
"""

from http.server import HTTPServer, SimpleHTTPRequestHandler
from urllib.parse import parse_qs
import requests
import threading
import webbrowser
import os

# 1. 最新 Cookie（若 Cookie 过期，请替换下面字典）
COOKIES = {
    'bzb_jsxsd':   'D98A554A1C305157E27A5E64B246AAD3',
    'SERVERID_gld':   'pc121',
    'SERVERID_jsxsd': 'njxpc135',
    'bzb_njw':   'DC5A0010D26117197FCFCA6B211CA486'
}

HEADERS = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36',
    'X-Requested-With': 'XMLHttpRequest'
}

class Handler(SimpleHTTPRequestHandler):
    def do_GET(self):
        if self.path.startswith('/api/kb'):
            try:
                # 解析周次参数
                query = parse_qs(self.path.split('?', 1)[1])
                zc = int(query.get('zc', ['1'])[0])
            except Exception:
                zc = 1

            # 拉课表
            url = 'https://jw.sdpt.edu.cn/jsxsd/framework/mainV_index_loadkb.htmlx'
            params = {
                'zc': zc,
                'kbjcmsid': '16FD8C2BE55E15F9E0630100007FF6B5',
                'xnxq01id': '2025-2026-1',
                'xswk': 'false'
            }
            try:
                resp = requests.get(url, params=params, cookies=COOKIES, headers=HEADERS, timeout=10)
                resp.raise_for_status()
                html = resp.text
            except Exception as e:
                html = f'拉取失败：{e}'

            # 返回
            self.send_response(200)
            self.send_header('Content-Type', 'text/plain; charset=utf-8')
            self.send_header('Access-Control-Allow-Origin', '*')
            self.end_headers()
            self.wfile.write(html.encode('utf-8'))
            return

        # 其余文件走默认静态文件
        super().do_GET()

def open_browser():
    webbrowser.open('http://localhost:8000')

if __name__ == '__main__':
    port = 8000
    os.chdir(os.path.dirname(os.path.abspath(__file__)))  # 确保静态文件目录正确
    server = HTTPServer(('0.0.0.0', port), Handler)
    print(f'Server started at http://localhost:{port}')
    threading.Timer(1, open_browser).start()
    server.serve_forever()